import hashlib
import sqlite3
import threading
import time
from datetime import datetime, timedelta
from flask import Flask, request, jsonify
from CalcTools import CalcServe, tasklist, started_queue, AdminAndLogin
from Entity import Task, StartedTask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
db_file_name = 'db_file'
table_name = 'table_name'
AdminAndLogin.create_user_table()


# 添加待办事项
@app.route('/add_task', methods=['POST', 'GET'])
def add_task():
    """
    # todo { user_id:
    #        task_id:
    #        description:
    #        category:
    #        during:
    #        priority:
    #        start=False
    #  }
    :return:
    """
    data = request.get_json()
    todo = data.get('task')
    task = Task(user_id=todo['user_id'], task_id=todo['task_id'],
                description=todo['description'], category=todo['category'],
                during=todo['during'], priority=todo['priority'], start=False)
    tasklist.add_task(task)
    for task in tasklist.tasks:
        print(task)
    return jsonify({'message': 'Task added successfully'})


# 获取待办事项列表
@app.route('/get_list', methods=['GET'])
def get_list():
    result = tasklist.get_list()
    return jsonify({'message': 'get_list successfully',
                    'result': result})


# 删除待办事项
@app.route('/delete_task/<int:task_id>', methods=['DELETE'])
def delete_task():
    data = request.get_json()
    task_id = data.get('task_id')
    tasklist.delete_task(task_id)
    return jsonify({'message': 'Task deleted successfully'})


# 修改待办事项
@app.route('/modify_task/<int:task_id>', methods=['POST'])
def modify_task():
    data = request.get_json()
    task_id = data.get('task_id')
    attribute = data.get('attribute')
    information = data.get('information')
    tasklist.modify_task(task_id, attribute, information)
    return jsonify({'message': 'Task modified successfully'})


# 查找待办事项
@app.route('/find_task/<int:task_id>', methods=['GET'])
def find_task():
    data = request.get_json()
    task_id = data.get('task_id')
    index = tasklist.find_index(task_id)
    task = tasklist.find_task(index)
    return jsonify({'message': 'Task found successfully',
                    'task': task})


# 任务
@app.route('/finish_task/<int:task_id>', methods=['PATCH'])
def finish_task():
    data = request.get_json()
    task_id = data.get('task_id')
    start_time_str = data.get('start_time_str')
    end_time_str = data.get('end_time_str')
    task = tasklist.pop_task(task_id)
    started_task = StartedTask(start_time_str, end_time_str,
                               task.user_id, task.task_id, task.description,
                               task.category, task.priority, task.during)
    started_queue.append_task(started_task)


# 获取每天的统计数据
@app.route('/get_statistics', methods=['GET'])
def get_statistics():
    """
    :param {
            date_time_str: "2019-0-01 20:00:00"
            freq: day/week/month
                }
    :return: {  focus_hour: time
                finish_task: num
                task_percentage:{ work: 0.1
                                  play: 0.2
                                  eat:  0.7 }
            }
    """
    data = request.get_json()
    date_time_str = data.get('date_time_str')
    freq = data.get('freq')
    daily_focus_hour = CalcServe.df_cal_focus_hour(date_time_str, freq, db_file_name, table_name)
    daily_task = CalcServe.df_cal_num_finished_task(date_time_str, freq, db_file_name, table_name)
    daily_task_percentage = CalcServe.df_cal_percentage(date_time_str, freq, db_file_name, table_name)
    result = {'focus_hour': daily_focus_hour,
              'number_of_finished_task': daily_task,
              'finished_task_percentage': daily_task_percentage
              }
    return jsonify(result)


@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    hashed_password = hashlib.sha256(password.encode()).hexdigest()
    conn = sqlite3.connect("user.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hashed_password))
    conn.commit()
    conn.close()
    return jsonify({"message": "Registration successful!"})


@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    hashed_password = hashlib.sha256(password.encode()).hexdigest()
    conn = sqlite3.connect("user.db")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, hashed_password))
    user = cursor.fetchone()
    conn.close()
    if user is not None:
        return jsonify({"message": "Login successful!"})
    return jsonify({"message": "Login failed. Please check your username and password."})


@app.route('/test', methods=['GET'])
def test():
    return jsonify({"message": "test"})


# 获取每周的统计数据
# 计算和午夜相差时间
# 计算距离午夜还有多少秒
def time_until_midnight():
    now = datetime.now()
    tomorrow_midnight = datetime(now.year, now.month, now.day) + timedelta(days=1)
    time_difference = tomorrow_midnight - now
    return time_difference.total_seconds()


# 每隔24小时清空队列生成缓存表
def scheduled_task():
    while True:
        # 执行任务
        # print(started_queue.started_tasks)
        started_queue.push_to_sql()  # 调用函数
        # 打印或记录日志以便跟踪任务的执行情况
        print("Task executed at", datetime.now())
        df = CalcServe.get_df("2023-05-01 09:06:00", "day", 'db_file', 'table_name')
        # print("first_df")
        print(df)
        # 等待24小时
        time.sleep(5)  # 每隔24小时触发一次，单位为秒


def create_thread():
    # 创建并启动定时任务线程
    timer_thread = threading.Thread(target=scheduled_task)
    timer_thread.daemon = True  # 设置为守护线程，主线程结束时自动退出
    timer_thread.start()


if __name__ == '__main__':
    # create_thread()
    # conn = sqlite3.connect(db_file_name)
    # cursor = conn.cursor()
    # cursor.execute(f"DELETE FROM {table_name}")
    # conn.commit()
    # conn.close()
    # task1 = Task(user_id=1, task_id=1, description="Task 1", category="Work", priority=1, start=False, during=2)
    # task2 = Task(user_id=1, task_id=2, description="Task 2", category="Personal", priority=1, start=False,
    #              during=60)
    # task3 = Task(user_id=1, task_id=3, description="Task 3", category="Dajiao", priority=1, start=False,
    #              during=40)
    # task4 = Task(user_id=1, task_id=4, description="Task 4", category="valorant", priority=1, start=False,
    #              during=50)
    #
    # tasklist.add_task(task1)
    # tasklist.add_task(task2)
    # tasklist.add_task(task3)
    # tasklist.add_task(task4)
    # tasklist.sorted_task()
    # # 保存开始后的任务
    # start_time_str1 = "2023-05-01 09:06:00"
    # end_time_str1 = "2023-05-01 09:08:00"
    # end_time_str2 = "2023-06-02 09:08:00"
    # end_time_str3 = "2023-05-01 15:08:00"
    # end_time_str4 = "2023-05-01 18:08:00"
    # finished_task1 = StartedTask(start_time_str1, end_time_str1,
    #                              task1.user_id, task1.task_id, task1.description,
    #                              task1.category, task1.priority, task1.during)
    # finished_task2 = StartedTask(start_time_str1, end_time_str2,
    #                              task2.user_id, task2.task_id, task2.description,
    #                              task2.category, task2.priority, task2.during)
    # finished_task3 = StartedTask(start_time_str1, end_time_str3,
    #                              task3.user_id, task3.task_id, task3.description,
    #                              task3.category, task3.priority, task3.during)
    # finished_task4 = StartedTask(start_time_str1, end_time_str4,
    #                              task4.user_id, task4.task_id, task4.description,
    #                              task4.category, task4.priority, task4.during)
    # started_queue.append_task(finished_task1)
    #
    # started_queue.append_task(finished_task2)
    # started_queue.append_task(finished_task3)
    # started_queue.append_task(finished_task4)
    # started_queue.push_to_sql()
    app.run(debug=True)
    # print((CalcServe.df_cal_percentage("2023-05-01 09:06:00", "month", 'db_file', 'table_name')))
